<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { getFldm } from '@/utils/get-fldm'
import yspglService from '@/api/yspgl'
import { useRoute } from 'vue-router'
import dayjs from 'dayjs'

const emit = defineEmits(['refresh'])

const route = useRoute()

const isLoading = ref()
const saveLoading = ref(false)
// 入参

// 生命周期
onMounted(() => {
  // 查询责任者（单位树）
  // queryDwTree()
  // 获取音视频类别（分类代码）
  // getYsplb()
  // 获取密级（分类代码）
  getMj()
  // 获取保管期限（分类代码）
  getBgqx()
  // 获取录制单位（分类代码）
  // getLzdw()
})

/*
 * 获取音视频类别（分类代码）
 */
const ysplbList = ref()
const getYsplb = async () => {
  ysplbList.value = await getFldm('gd021')
}

/*
 * 获取密级（分类代码）
 */
const mjList = ref()
const getMj = async () => {
  mjList.value = await getFldm('gd006')
}

/*
 * 获取保管期限（分类代码）
 */
const bgqxList = ref()
const getBgqx = async () => {
  bgqxList.value = await getFldm('gd020')
}

// 获取录制单位（分类代码）
const lzdwList = ref()
const getLzdw = async () => {
  lzdwList.value = await getFldm('gd020')
}

const mjChange = (value: number) => {
  ruleForm.value.mjdm = mjList.value[value].dm
  ruleForm.value.mjmc = mjList.value[value].mc
}

const bgqxChange = (value: number) => {
  ruleForm.value.bgqxdm = bgqxList.value[value].dm
  ruleForm.value.bgqxmc = bgqxList.value[value].mc
}

/* 弹框状态 */
const dialogVisible = ref(false)

/*
 * 打开弹框
 */
/* 获取节点信息 */
const nodeData = ref<any>([])
const openDialog = (node: any) => {
  nodeData.value = node
  ruleForm.value.mjdm = mjList.value[0]?.dm
  ruleForm.value.mjmc = mjList.value[0]?.mc
  ruleForm.value.bgqxdm = bgqxList.value[0]?.dm
  ruleForm.value.bgqxmc = bgqxList.value[0]?.mc
  ruleForm.value.nd = dayjs(Date.now()).format('YYYY')
  dialogVisible.value = true
}

const ruleFormRef = ref<FormInstance>()

const ruleForm = ref({
  bgqxdm: '',
  bgqxmc: '',
  bz: '',
  dabh: '',
  mjdm: '',
  mjmc: '',
  mlbh: '',
  nd: '',
  paz: '',
  psdd: '',
  psrq: '',
  sxh: 0,
  sxmlmc: '',
  tjr: '',
})

/* 表单校验 */
const rules = ref<FormRules>({
  sxmlmc: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur',
    },
  ],
  nd: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur',
    },
  ],
  tjr: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur',
    },
  ],

  paz: [
    {
      required: true,
      message: '请选择',
      trigger: 'blur',
    },
  ],
  psdd: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur',
    },
  ],
  psrq: [
    {
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  ],
  mjmc: [
    {
      required: true,
      message: '请选择',
      trigger: 'blur',
    },
  ],
  bgqxmc: [
    {
      required: true,
      message: '请选择',
      trigger: 'blur',
    },
  ],
})

/*
 * 关闭弹框
 */
const closeDialog = () => {
  nextTick(() => {
    ruleFormRef.value?.resetFields()
    ruleForm.value.bz = ''
  })
  dialogVisible.value = false
}

/*
 * 保存（成功抛出刷新）
 */
const save = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      const params = {
        ...ruleForm.value,
        dabh: nodeData.value.dabh,
        sxh: nodeData.value.mlsxh,
        cbdwmc: route.query.cbdwmc,
        cbbmmc: route.query.cbbmmc,
        mllydm: 'gd0590001',
      }
      saveLoading.value = true
      yspglService
        .saveZpml(params, route.query.ajbh as string)
        .then(() => {
          ElMessage({
            type: 'success',
            message: '保存成功',
          })
          emit('refresh', nodeData.value.bh)
          closeDialog()
        })
        .catch((err) => {
          !err.isError && ElMessage({ type: 'warning', message: err.message })
        })
        .finally(() => {
          saveLoading.value = false
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}

/*
 * 保存并添加（成功抛出刷新）
 */
const saveAdd = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      const params = {
        ...ruleForm.value,
        dabh: nodeData.value.dabh,
        sxh: nodeData.value.mlsxh,
        cbdwmc: route.query.cbdwmc,
        cbbmmc: route.query.cbbmmc,
        mllydm: 'gd0590001',
      }
      yspglService
        .saveZpml(params, route.query.ajbh as string)
        .then(() => {
          ElMessage({
            type: 'success',
            message: '保存成功',
          })
          nextTick(() => {
            ruleFormRef.value?.resetFields()
            ruleForm.value.bz = ''
          })
          emit('refresh', nodeData.value.bh)
        })
        .catch((err) => {
          !err.isError && ElMessage({ type: 'warning', message: err.message })
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}

defineExpose({ openDialog })
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加照片目录"
    width="50%"
    :close-on-click-modal="false"
    :before-close="closeDialog"
  >
    <el-form ref="ruleFormRef" label-width="auto" :model="ruleForm" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="题名" prop="sxmlmc">
            <el-input
              v-model="ruleForm.sxmlmc"
              maxlength="30"
              placeholder="请输入"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年度" prop="nd">
            <!-- <el-input-number
              :controls="false"
              v-model="ruleForm.nd"
              placeholder="请输入"
              style="width: 100%"
            /> -->
            <el-input
              v-model="ruleForm.nd"
              maxlength="4"
              @input="ruleForm.nd = ruleForm.nd.replace(/[^\d.]/g, '').trim()"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="提交人" prop="tjr">
            <el-input v-model="ruleForm.tjr" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="拍摄者" prop="paz">
            <el-input v-model="ruleForm.paz" placeholder="请输入" />
            <!-- <el-date-picker
              width="100%"
              v-model="ruleForm.zrz"
              type="date"
              placeholder="请选择"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            /> -->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="拍摄地点" prop="psdd">
            <el-input v-model="ruleForm.psdd" placeholder="请输入" />
            <!-- <el-date-picker
              width="100%"
              v-model="ruleForm.zrz"
              type="date"
              placeholder="请选择"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            /> -->
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="拍摄时间" prop="psrq" style="width: 100%">
            <el-date-picker
              style="width: 100%"
              v-model="ruleForm.psrq"
              type="date"
              placeholder="请选择"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="密级" prop="mjmc" style="width: 100%">
            <!-- <el-input v-model="ruleForm.mjmc" placeholder="请输入责任者" /> -->
            <el-select
              v-model="ruleForm.mjmc"
              clearable
              placeholder="请选择"
              style="width: 100%"
              @change="mjChange"
            >
              <el-option
                v-for="(zrritem, index) in mjList"
                :key="zrritem.dm"
                :label="zrritem.mc"
                :value="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="保管期限" prop="bgqxmc" style="width: 100%">
            <el-select
              v-model="ruleForm.bgqxmc"
              clearable
              placeholder="请选择"
              style="width: 100%"
              @change="bgqxChange"
            >
              <el-option
                v-for="(zrritem, index) in bgqxList"
                :key="zrritem.dm"
                :label="zrritem.mc"
                :value="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input
              type="textarea"
              :row="6"
              maxlength="500"
              v-model="ruleForm.bz"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="save(ruleFormRef)" :loading="saveLoading">保存</el-button>
        <el-button type="primary" @click="saveAdd(ruleFormRef)" :loading="isLoading"
          >保存并添加</el-button
        >
        <el-button @click="closeDialog">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
}
</style>
